package com.itheima.service.impl;

import com.itheima.DTOAndVO.OrderVO;
import com.itheima.DTOAndVO.SubmitOrderDTO;
import com.itheima.common.constant.MessageConstant;
import com.itheima.common.utils.DateUtils;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private MemberDao memberDao;
    /**
     * 体检预约
     * @param submitOrderDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer submitOrder(SubmitOrderDTO submitOrderDTO) throws Exception {
//        2. 校验用户输入的验证码是否正确。
        String code =(String) redisTemplate.opsForValue().get(submitOrderDTO.getTelephone()); //从redis中获取验证码
        if (!submitOrderDTO.getValidateCode().equals(code)){
            throw new Exception(MessageConstant.VALIDATECODE_ERROR);
        }

//        3. 预约日期的预约人数没有设置的话不能预约。
        Date date= DateUtils.parseString2Date(submitOrderDTO.getOrderDate(),"yyyy-MM-dd");
        OrderSetting orderSetting= orderSettingDao.find_ordersetting_number(date); //查找该日期的相关信息

        if (orderSetting==null){
            throw new Exception("根据预约日期"+MessageConstant.GET_ORDERSETTING_FAIL);
        }
        if (orderSetting.getNumber()<=0){
            throw new Exception("可预约人数没有设置");
        }
//        4. 预约日期是否已经约满，如果已经约满则无法预约。
        if (orderSetting.getNumber()==orderSetting.getReservations()){
            throw new Exception(MessageConstant.ORDER_FULL);
        }

//        5. 不能重复预约（同一个用户在同一天预约了同一个套餐）。
        Integer setmealId=Integer.parseInt(submitOrderDTO.getSetmealId());
        List<Order> orderList= orderDao.findByNameAndOrderDate(date,submitOrderDTO.getName(),setmealId);
        log.info("orderList:{}",orderList);
        if (orderList!=null && orderList.size()>0){
            throw new Exception(MessageConstant.HAS_ORDERED);
        }
//        6. 当前用户不是会员，需要自动完成注册。(查询此人是否存在)
        Member member=memberDao.findByNameAndIdCard(submitOrderDTO.getName(),submitOrderDTO.getIdCard());

        if (member==null){
            member=new Member();
            member.setIdCard(submitOrderDTO.getIdCard());
            member.setName(submitOrderDTO.getName());
            member.setSex(submitOrderDTO.getSex());
            member.setPhoneNumber(submitOrderDTO.getTelephone());
            member.setRegTime(java.sql.Date.valueOf(LocalDate.now()));
            log.info("自动注册会员：{}",member);
            memberDao.insert(member);  //返回id
        }

//        7. 更新已预约人数
        Order order=new Order();
        order.setOrderDate(date);
        order.setOrderStatus(Order.ORDERSTATUS_NO);
        order.setOrderType(Order.ORDERTYPE_WEIXIN);
        order.setSetmealId(Integer.parseInt(submitOrderDTO.getSetmealId()));
        order.setMemberId(member.getId());

        orderDao.insert(order);  //返回id
        orderSettingDao.update(date); //已预约人数+1

        return order.getId();
    }

    /**
     * 根据预约id查询预约信息
     * @param id
     * @return
     */
    @Override
    public OrderVO findById(String id) {
        Integer orderId= Integer.parseInt(id);
        OrderVO orderVO= orderDao.findById(orderId);
        return orderVO;
    }

}
